package com.financing.wap.web.controller.api;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.financing.mail.service.MailSenderService;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.common.Session;
import com.financing.wap.dto.ActivitesAnswerDTO;
import com.financing.wap.dto.ActivitesDTO;
import com.financing.wap.dto.AuthenticationDTO;
import com.financing.wap.dto.FaUserDTO;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.IAccountService;
import com.financing.wap.service.IActivitesService;
import com.financing.wap.service.IAnswerService;
import com.financing.wap.service.IAuthenticationService;
import com.financing.wap.service.ICheckCodeService;
import com.financing.wap.service.IProductService;
import com.financing.wap.service.ISmsService;
import com.financing.wap.service.IUserService;
import com.financing.wap.util.ActiviesRuleUtils;
import com.financing.wap.util.Constants;
import com.financing.wap.util.IPUtil;
import com.financing.wap.util.MessageUtil;
import com.financing.wap.util.PropertiesUtils;
import com.financing.wap.util.SecureUtil;
import com.financing.wap.util.StringUtil;
import com.financing.wap.util.VerifyCodeUtils;
import com.financing.wap.web.controller.BaseController;


/**
 * 问卷调查哦活动专属controller
 * @author Mars
 * @createDate 2014年11月24日
 */
@Controller("apiActivityQuestionController")
@RequestMapping("/api/question")
public class ActivityQuestionController extends BaseController {
	Logger logger = Logger.getLogger(getClass());

	@Autowired
	private IUserService userService;

	@Autowired
	public ISmsService smsService;

	@Autowired
	private IAccountService accountService;

	@Autowired
	private MailSenderService mailSenderService;

	@Autowired
	private IProductService productService;

	@Autowired
	private ICheckCodeService checkCodeServiceImpl;

	@Autowired
	private IAnswerService answerService;
	
	@Autowired
	public IAuthenticationService authenticationService;
	
	@Autowired
	public IActivitesService activitesService;
	
	/**
	 * 问卷登录，新用户注册，老用户登录
	 * @param mobile 手机号
	 * @param vCode 验证码
	 * @param sourceCode 来源码
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("questionLogin")
	@ResponseBody
	public ResultMap questionLogin(String mobile,String vCode,String sourceCode,HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();
		//验证码校验
		String platformtype = request.getParameter("platformtype");
//		1pc,2app ,默认pc
		boolean isOut = activitesService.isOutDateByCode(Constants.ACTIVITIES_CODE_DCWJ);
		if(isOut){
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.ACTIVITIES_DATE_IS_OUT);
			result.setMessage("货期未开始或已过期");
			return result;
		}
		if(StringUtils.isBlank(mobile)||StringUtils.isBlank(vCode)){
			//参数验证
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
			result.setMessage("mobile or vCode is null!");
			return result;
		}
		if(!StringUtil.isMobile(mobile)){//验证短息30分钟内有效
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_TYPE_ERROR);
			result.setMessage("类型不对！");
			return result;
		}
		try {
			
			
			Integer activety_otp_time= new Integer(PropertiesUtils.getValue("activety_otp_time")); 
			logger.info("start check OTP~");
			logger.info("activity time is "+activety_otp_time+" m");
			
			
			
			if(StringUtils.isEmpty(platformtype)||!"2".equals(platformtype)){
				String verifyCode = (String)SessionUtil.getSession().getAttribute(Constants.SESSION_KEY_VERIFYCODE);
				String requestVerifyCode = request.getParameter("verifyCode");
				SessionUtil.getSession().setAttribute(Constants.SESSION_KEY_VERIFYCODE, null);
				log.info("verifyCode is :"+verifyCode);
				log.info("requestVerifyCode is :"+requestVerifyCode);
				if(StringUtils.isEmpty(verifyCode)||!verifyCode.equals(requestVerifyCode.toLowerCase())){
					result.setStatus(STATUS.FAILE);
					result.setStatusCode(ResultMap.LOGIN_VERIFYCODE_ERROR);
					result.setMessage("图片验证码错误");
					return result;
				}
			}
			if(checkCodeServiceImpl.CheckCodeSwitch() && !vCode.equalsIgnoreCase(getOtpCode(mobile))){//验证码校验
				log.info("error otpcode");
				//校验验证码--未通过
				result.setStatus(ResultMap.STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_OTP_VALIDATE_ERROR);
				result.setMessage("手机验证码不正确！");
				return result;
			}
			
			if(checkCodeServiceImpl.CheckCodeSwitch() && checkOtpCodeTimeOut(mobile,activety_otp_time,ISmsService.OTP_CODE_FIRST_TIME)){//验证短息30分钟内有效
				result.setStatus(ResultMap.STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_OTP_VALIDATE_ERROR_TIMEOUT);
				result.setMessage("手机验证码超时！");
				return result;
			};


			log.info("activity start register");
			UserDTO user = new UserDTO();
			user.setMobile(mobile);
			user.setLoginName(mobile);
			user = userService.queryUserByMobile(user); 
			if(user==null){//注册新用户
				user = new UserDTO();
				//对密码进行加密
				String password = VerifyCodeUtils.generateVerifyCode(6,VerifyCodeUtils.VERIFY_CODES_NUM);
				String securePassword = SecureUtil.MD5EncryptAndBase64(password);
				user.setLoginName(mobile);
				user.setMobile(mobile);
				user.setPassword(securePassword);
				user.setMediaSource(Constants.ACTIVITIES_CODE_DCWJ);//
				String sourceCodeInt = "0";
				if(StringUtils.isNotBlank(sourceCode)){
					sourceCodeInt = sourceCode;
				}
				user.setSourceCode(sourceCodeInt);
				//创建用户
				userService.registerUser(user);
				
				user = userService.queryUserByMobile(user); 
				logger.info("注册成功！");
				
				accountService.shareGiftActivites(new BigDecimal(PropertiesUtils.getValue("activety_register_money")),user.getId(),sourceCode);
				logger.info("分享送1111元成功！");
				
				/****将随机密码发送至客户手机****/
				Map<String,Object>  params = new HashMap<String,Object>();
				//			passWordc
				params.put("passWord", password);
				Map<String,Object> m  = MessageUtil.getMessage("messageAndMail","activityRegister",params);
				//			String title = (String)m.get(MessageUtil.KEY_TITLE);
				String content = (String)m.get(MessageUtil.KEY_CONTENT);
				logger.info("将随机密码发送至客户手机");
				smsService.sendOtpMessage(mobile, content,Constants.regPasswdSmsAd);
			}
			//自动登录
//			user = userService.getUserByUF(user);
			
			Session session = getSession(true);
			session.setLogin(true);
			session.setUser(user);
			setSession(session);
			/** 返回的user信息*/
			AuthenticationDTO auth = authenticationService.queryAuthInfo(user.getId());
			result.setAttribute("userType", user.getUType());
			result.setAttribute("uRole", user.getRole());
			result.setAttribute("reviewStatus", "0");
			if(auth!=null){
				result.setAttribute("reviewStatus", auth.getReviewStatus());
			}
			if(StringUtils.isBlank(user.getUserName())){
				result.setAttribute("uName",user.getMobile());
			}else{
				result.setAttribute("uName",user.getUserName());
			}
			result.setAttribute("id", user.getId());
			result.setAttribute("loginName", result.getAttribute("loginName"));
			result.setAttribute("uImage", user.getuImage());
//			 json.attributes.loginName;
//				$scope.user.id = json.attributes.id;
//				$scope.user.image = json.attributes.uImage;
			/**返回的user信息END*/
			
			result.setStatus(ResultMap.STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setMessage("登录成功!");
			logger.info("获取活动短信信息");

			ActivitesAnswerDTO queryDto = new ActivitesAnswerDTO();
			queryDto.setSessionId(request.getSession().getId());
			List<ActivitesAnswerDTO> answerList = answerService.searchAnswerByParas(queryDto);
			/** 开始活动  */
			if(answerList==null||answerList.size()==0){
				logger.info("没有分数");
				result.setStatus(ResultMap.STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_ACTIVITIES_NO_SCORE);
				result.setMessage("当前session用户没有分数记录");
				return result;
			}
			queryDto = answerList.get(0);
			if(queryDto.getuId()!=null){
				logger.info("一份答案重复提交~");
				result.setStatus(ResultMap.STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_ACTIVITIES_ANSWER_RESUBMIT);
				result.setMessage("同一份答案不可以被多次提交！");
				return result;
			}
			
			
			//重复领取认证
			ActivitesAnswerDTO renameRueryDto = new ActivitesAnswerDTO();
			renameRueryDto.setuId(user.getId());
			List<ActivitesAnswerDTO> list = answerService.searchAnswerByParas(renameRueryDto);
			//重复领取认证END
			if(!(list==null||list.isEmpty())){
				result.setStatus(ResultMap.STATUS.ERROR);
				ActivitesAnswerDTO aa =list.get(0);
				String uId = aa.getuId();
				if(uId==null){
					Integer score = aa.getScore();
					result.setAttribute("score",score);
					result.setStatusCode(ResultMap.STATUS_CODE_ACTIVITIES_HAS_JOIN_NO_LOGIN);
					result.setMessage("已经参与过此调查,但并未登录过");
				}else{
					result.setStatusCode(ResultMap.STATUS_CODE_ACTIVITIES_HAS_JOIN);
					result.setMessage("已经参与过此调查,并已经绑定uid");
				}
				
				
				return result;
			}
			
			
			//最后登录地+登录IP
			FaUserDTO userTmp = new FaUserDTO();
			userTmp.setId(user.getId());
			userTmp.setLastLoginIP(IPUtil.getRemoteHost(request));
			userTmp.setLastLoginTime(new Date());
			userService.updateFaUserInfo(userTmp);
			
			answerService.updateAccountAndAnswer(user.getId(),queryDto.getSessionId(),user.getAccountId(),new BigDecimal(queryDto.getScore()));
			
			return result;
		}catch(Exception e) {
			logger.error("==>error messang:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			result.setMessage("注册失败!");
		}
		return result;
	} 


	/**
	 * 得到奖励金额
	 * @param answerJson 答案qajson
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("score")
	@ResponseBody
	public ResultMap getScore(String qajson,HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();
		boolean isOut = activitesService.isOutDateByCode(Constants.ACTIVITIES_CODE_DCWJ);
		if(isOut){
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.ACTIVITIES_DATE_IS_OUT);
			result.setMessage("货期未开始或已过期");
			return result;
		}
		if(StringUtils.isBlank(qajson)){
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_ACTIVITIES_NO_ANSWER);
			result.setMessage("没有答案");
			return result;
		}
		//答案map
		Map<String,String> answerMap = ActiviesRuleUtils.getAnswerMap(qajson);

		if(answerMap.size()==0){
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_ACTIVITIES_NO_ANSWER);
			result.setMessage("没有答案");
			return result;
		}
		
		try{
			String sessionId = request.getSession().getId();
			ActivitesAnswerDTO queryDto = new ActivitesAnswerDTO();
			queryDto.setSessionId(sessionId);
			List<ActivitesAnswerDTO> list = answerService.searchAnswerByParas(queryDto);
			if(!(list==null||list.isEmpty())){
				result.setStatus(ResultMap.STATUS.ERROR);
				ActivitesAnswerDTO aa =list.get(0);
				String uId = aa.getuId();
				if(uId==null){
					Integer score = aa.getScore();
					result.setAttribute("score",score);
					result.setStatusCode(ResultMap.STATUS_CODE_ACTIVITIES_HAS_JOIN_NO_LOGIN);
					result.setMessage("已经参与过此调查,但并未登录过");
				}else{
					result.setStatusCode(ResultMap.STATUS_CODE_ACTIVITIES_HAS_JOIN);
					result.setMessage("已经参与过此调查,并已经绑定uid");
				}
				
				
				return result;
			}
			boolean isfull = isFullInWeek();
			Integer score = ActiviesRuleUtils.questionScore(ActiviesRuleUtils.questionLevel(answerMap),isfull);
			logger.info("活动奖励：score："+score);
			List<ActivitesAnswerDTO>  answerList  = getAnswerList(qajson,score,sessionId);
			
		 
			for(ActivitesAnswerDTO qaDto:answerList){
				answerService.insertAnswer(qaDto);
			}
			result.setAttribute("score", score);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setMessage("问卷成功完成");
		}catch(Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			result.setMessage("转发失败!");
		}

		return result;
	} 

	
	
	/**
	 * 将答案json转成集合
	 * @param jsonStr
	 * @return
	 */
	private List<ActivitesAnswerDTO> getAnswerList(String jsonStr,Integer score,String sessionId){
		List<ActivitesAnswerDTO> alist = new ArrayList<ActivitesAnswerDTO>();
		JSONObject json = JSON.parseObject(jsonStr);
		Set<String> keySet = json.keySet();
		Iterator<String> keyIterator = keySet.iterator();
		ActivitesAnswerDTO dto = null;
		while(keyIterator.hasNext()){
			String key = keyIterator.next();
			String values = json.get(key).toString();
			String[] valueArray = values.split(",");
			for(int i=0;i<valueArray.length;i++){
				dto = new ActivitesAnswerDTO();
				dto.setScore(score);
				dto.setqId(new Integer(ActiviesRuleUtils.getQuestionId(key)));//问题ID
				dto.setAnswer(valueArray[i]);//答案
				dto.setSessionId(sessionId);
				dto.setActiviesCode(Constants.ACTIVITIES_CODE_DCWJ);
				alist.add(dto);
			}
		}
		return alist;
	}
	
	/**
	 * 判断一周内500的奖励额是否超过2个
	 * @return
	 */
	private boolean isFullInWeek(){
		ActivitesDTO activitesDto = activitesService.searchActivitesByCode(Constants.ACTIVITIES_CODE_DCWJ);
		Date startDate = activitesDto.getActiviesStartTime();
		Date endDate = activitesDto.getActiviesEndTime();
//		Date startDate = DateUtil.format("2014-11-01", "yyyy-MM-dd");
//		Date endDate = DateUtil.format("2014-11-30", "yyyy-MM-dd");
		Date currentDate = new Date();
		Date queryStartDate=null;
		Date queryEndDate=null;
		Calendar cal = Calendar.getInstance();
		cal.setTime(startDate);
		//第一周
		cal.add(Calendar.WEEK_OF_MONTH, 1);
		Date oneWeekEnd =cal.getTime();
		if(currentDate.before(oneWeekEnd)&&currentDate.after(startDate)){
			queryStartDate = startDate;
			queryEndDate = oneWeekEnd;
			
			Map<String,Date> p = new HashMap<String,Date>();
			p.put("startDate", queryStartDate);
			p.put("endDate", queryEndDate);
			Integer count = answerService.searchCountOneWeek(p);
			if(count<2){
				return false;
			}
		}
		//第二周
		cal.add(Calendar.WEEK_OF_MONTH, 1);
		Date twoWeekEnd =cal.getTime();
		if(currentDate.before(twoWeekEnd)&&currentDate.after(oneWeekEnd)){
			queryStartDate = oneWeekEnd;
			queryEndDate = twoWeekEnd;
	 
			Map<String,Date> p = new HashMap<String,Date>();
			p.put("startDate", queryStartDate);
			p.put("endDate", queryEndDate);
			Integer count = answerService.searchCountOneWeek(p);
			if(count<2){
				return false;
			}
		}
		//第三周
		cal.add(Calendar.WEEK_OF_MONTH, 1);
		Date threeWeekEnd =cal.getTime();
		if(currentDate.before(threeWeekEnd)&&currentDate.after(twoWeekEnd)){
			queryStartDate = twoWeekEnd;
			queryEndDate = threeWeekEnd;
	 
			Map<String,Date> p = new HashMap<String,Date>();
			p.put("startDate", queryStartDate);
			p.put("endDate", queryEndDate);
			Integer count = answerService.searchCountOneWeek(p);
			if(count<2){
				return false;
			}
		}
		//最后一周到结束日期
		if(currentDate.before(endDate)&&currentDate.after(threeWeekEnd)){
			queryStartDate = threeWeekEnd;
			queryEndDate = endDate;
		 
			Map<String,Date> p = new HashMap<String,Date>();
			p.put("startDate", queryStartDate);
			p.put("endDate", queryEndDate);
			Integer count = answerService.searchCountOneWeek(p);
			if(count<2){
				return false;
			}
		}
		return true;
	}
	
	public static void main(String[] orgs){
		
		String sourceCode = "ddsf";
		System.out.println(sourceCode.matches("[0-9]+"));
		

	}
}
